package com.moco.launcher.adapter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;

public class CycleViewOnPageChangeListener implements OnPageChangeListener {

	private OnPageChangeListener mListener;
	private Object mViewPager;
	private PagerAdapter mAdapter;
	private int mPosition = 0;
	private Class<? extends Object> mClazz;

	public CycleViewOnPageChangeListener(OnPageChangeListener listener,
			PagerAdapter adapter, Object viewpager) {
		mListener = listener;
		mViewPager = viewpager;
		mAdapter = adapter;
		
		try {
			mClazz = mViewPager.getClass();
			Method getOffscreenPageLimit = mClazz.getMethod("getOffscreenPageLimit");
			Method setOffscreenPageLimit = mClazz.getMethod("setOffscreenPageLimit", int.class);
			int limit = (Integer)getOffscreenPageLimit.invoke(mViewPager);
			if (limit != 1)
				setOffscreenPageLimit.invoke(mViewPager, 1);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		try {
			Method setCurrentItem = null;
			setCurrentItem = mClazz.getMethod("setCurrentItem", int.class, boolean.class);
			if (arg0 == ViewPager.SCROLL_STATE_IDLE) {
				if (mPosition == mAdapter.getCount() + 1) 
					setCurrentItem.invoke(mViewPager, 1, false);
				else if (mPosition == 0)
					setCurrentItem.invoke(mViewPager, mAdapter.getCount(), false);
			}

			if (null != mListener)
				mListener.onPageScrollStateChanged(arg0);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		mPosition = arg0;
		if (null != mListener)
			mListener.onPageScrolled(arg0, arg1, arg2);
	}

	@Override
	public void onPageSelected(int arg0) {
		if (null != mListener)
			mListener.onPageSelected(arg0);
	}

}
